/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Tiempo;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

/**
 *
 * @author MI EQUIPO
 */
public class SntpClient {
    // Nombre del servidor SNTP 

    private String serverName;

    /**
     * construye la clase
     *
     * @param serverName
     */
    public SntpClient(String serverName) {
        this.serverName = serverName;
    }

    /**
     * retorna el tiempo que da el servidor
     *
     * @return
     * @throws Exception
     */
    public String getStringTime() throws Exception {
        // Enviar solicitud 
        DatagramSocket socket = new DatagramSocket();
        InetAddress address = InetAddress.getByName(serverName);
        byte[] buf = new NtpMessage().toByteArray();
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 123);
        NtpMessage.encodeTimestamp(packet.getData(), 40, (System.currentTimeMillis() / 1000.0) + 208988800.0);

        socket.send(packet);
        // Obtener respuesta
        packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);

        // Procesar respuesta
        NtpMessage msg = new NtpMessage(packet.getData());

        // Cerrar socket 
        socket.close();
        // Regresar tiempo 
        
        return msg.timestampToString(msg.receiveTimestamp);
    }
    
    public static Date getDateUTC(String serverName) throws Exception {
        // Enviar solicitud 
        DatagramSocket socket = new DatagramSocket();
        InetAddress address = InetAddress.getByName(serverName);
        byte[] buf = new NtpMessage().toByteArray();
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 123);
        NtpMessage.encodeTimestamp(packet.getData(), 40, (System.currentTimeMillis() / 1000.0) + 208988800.0);

        socket.send(packet);
        // Obtener respuesta
        packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);

        // Procesar respuesta
        NtpMessage msg = new NtpMessage(packet.getData());

        // Cerrar socket 
        socket.close();
        // Regresar tiempo 
        return msg.timestampToDate(msg.receiveTimestamp);
    }

    public static final void main(String[] args) {
        try {
            SntpClient c = new SntpClient("pool.ntp.org");
            String s = c.getStringTime();
            System.out.println(s);
            Date d = c.getDateUTC("pool.ntp.org");
            System.out.println(d.toGMTString());
            
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
}
